package net.jgrm.order.service.impl;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import net.jgrm.order.dto.CreateOrderRequest;
import net.jgrm.order.dto.OrderExportDTO;
import net.jgrm.order.dto.PaymentCallbackRequest;
import net.jgrm.order.dto.QueryOrderParams;
import net.jgrm.order.entity.Order;
import net.jgrm.order.entity.OrderItem;
import net.jgrm.order.entity.ReceiverInfo;
import net.jgrm.order.mapper.OrderItemMapper;
import net.jgrm.order.mapper.OrderMapper;
import net.jgrm.order.service.IOrderService;
import net.jgrm.order.utils.AESEncryptionUtil;
import net.jgrm.product.dto.ProductDTO;
import net.jgrm.product.dubbo.ProductDubboService;
import net.jgrm.redisadvanced.lock.RedisLockService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 订单服务实现类
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    private ProductDubboService productFeignService;

    @Autowired
    private AESEncryptionUtil aesEncryptionUtil;

    @Autowired
    private RedisLockService redisLockService;


    @DubboReference(version = "1.0.0", loadbalance = "random")
    private ProductDubboService productDubboService;

    @Override
    @GlobalTransactional(name = "create-order-feign", rollbackFor = Exception.class)
    public Order createOrderWithFeign(Long userId, Long productId, Integer quantity) {
        // 1. 查询商品信息
        ProductDTO product = productFeignService.getProductById(productId);
        if (product == null || product.getId() == null) {
            throw new RuntimeException("商品不存在");
        }

        // 2. 扣减库存
        boolean decreaseResult = productFeignService.decreaseStock(productId, quantity);
        if (!decreaseResult) {
            throw new RuntimeException("库存不足或扣减失败");
        }

        // 3. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNo(generateOrderNo());
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(quantity)));
        order.setStatus(1); // 已完成
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.insert(order);

        // 4. 创建订单项
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setProductId(productId);
        orderItem.setProductName(product.getProductName());
        orderItem.setProductPrice(product.getPrice());
        orderItem.setQuantity(quantity);
        orderItem.setTotalPrice(product.getPrice().multiply(new BigDecimal(quantity)));
        orderItemMapper.insert(orderItem);

        return order;
    }

    @Override
    @GlobalTransactional(name = "create-order-dubbo", rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public Order createOrderWithDubbo(Long userId, Long productId, Integer quantity) {
        // 1. 查询商品信息 - Dubbo调用
        ProductDTO product = productDubboService.getProductById(productId);
        if (product == null || product.getId() == null) {
            throw new RuntimeException("商品不存在");
        }
        // 2. 扣减库存 - Dubbo调用
        boolean decreaseResult = productDubboService.decreaseStock(productId, quantity);
        if (!decreaseResult) {
            throw new RuntimeException("库存不足或扣减失败");
        }
        int a = 1 / 0;
        // 3. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNo(generateOrderNo());
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(quantity)));
        order.setStatus(1); // 已完成
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.insert(order);

        // 4. 创建订单项
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setProductId(productId);
        orderItem.setProductName(product.getProductName());
        orderItem.setProductPrice(product.getPrice());
        orderItem.setQuantity(quantity);
        orderItem.setTotalPrice(product.getPrice().multiply(new BigDecimal(quantity)));
        orderItemMapper.insert(orderItem);

        return order;
    }

    @Override
    @GlobalTransactional(name = "create-order-with-receiver", rollbackFor = Exception.class)
    public Order createOrderWithReceiverInfo(CreateOrderRequest request) {
        log.info("Creating order with receiver info, userId: {}, productId: {}, quantity: {}",
                request.getUserId(), request.getProductId(), request.getQuantity());

        // 1. 参数验证
        validateCreateOrderRequest(request);

        // 2. 查询商品信息
        ProductDTO product = productFeignService.getProductById(request.getProductId());
        if (product == null || product.getId() == null) {
            throw new RuntimeException("商品不存在");
        }

        if (product.getStatus() != 1) {
            throw new RuntimeException("商品已下架");
        }

        // 3. 检查商品库存
        if (product.getStock() == null || product.getStock() < request.getQuantity()) {
            throw new RuntimeException("商品库存不足，当前库存: " + (product.getStock() == null ? 0 : product.getStock()));
        }

        // 4. 扣减库存
        boolean decreaseResult = productFeignService.decreaseStock(request.getProductId(), request.getQuantity());
        if (!decreaseResult) {
            throw new RuntimeException("库存扣减失败");
        }

        // 5. 创建订单（包含收货人信息）
        Order order = buildOrderWithReceiverInfo(request, product);
        // 使用自定义的加密插入方法
        insertOrderWithEncryption(order);

        // 6. 创建订单项
        OrderItem orderItem = buildOrderItem(order.getId(), request, product);
        orderItemMapper.insert(orderItem);

        log.info("Order created successfully with orderNo: {}", order.getOrderNo());
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handlePaymentCallback(PaymentCallbackRequest request) {
        String orderNo = request.getOrderNo();
        String transactionId = request.getTransactionId();
        Integer paymentStatus = request.getPaymentStatus();
        log.info("Processing payment callback, orderNo: {}, paymentStatus: {}, transactionId: {}",
                orderNo, paymentStatus, transactionId);

        // 使用订单号作为分布式锁的key
        String lockKey = "payment_callback_lock:" + orderNo;
        boolean locked = false;
        try {
            // 1. 获取分布式锁，设置超时时间为30秒
            locked = redisLockService.lock(lockKey, 30, TimeUnit.SECONDS);
            if (!locked) {
                log.warn("Failed to acquire distributed lock for payment callback, orderNo: {}", orderNo);
                return false; // 未能获取锁，返回处理失败
            }

            // 2. 再次查询订单，判断是否已经处理过（防止并发处理）
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            Order order = orderMapper.selectOne(queryWrapper);

            if (order == null) {
                log.error("Order not found, orderNo: {}", orderNo);
                return false;
            }

            // 3. 判断订单是否已经处理过
            if (order.getStatus() != 0) {
                log.info("Order has already been processed, current status: {}, orderNo: {}",
                        order.getStatus(), orderNo);
                // 订单已处理，返回成功（幂等性处理）
                return true;
            }

            // 4. 验证支付金额
            if (request.getPaymentAmount().compareTo(order.getTotalAmount()) != 0) {
                log.error("Payment amount mismatch, expected: {}, actual: {}, orderNo: {}",
                        order.getTotalAmount(), request.getPaymentAmount(), orderNo);
                return false;
            }

            // 5. 更新订单状态和交易信息
            order.setTransactionId(transactionId);
            // 将Long类型的时间戳转换为LocalDateTime
            if (request.getPaymentTime() != null) {
                order.setPaymentTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(request.getPaymentTime()), ZoneId.systemDefault()));
            }
            order.setUpdateTime(LocalDateTime.now());
            
            if (paymentStatus == 1) {
                // 支付成功
                order.setStatus(1);
                log.info("Payment successful, order status updated to paid, orderNo: {}", orderNo);
                
                // 支付成功后的业务逻辑，如通知库存服务释放预留库存等
                handlePaymentSuccess(order);
            } else {
                // 支付失败或取消
                order.setStatus(2); // 已取消
                log.info("Payment failed/cancelled, order status updated to cancelled, orderNo: {}", orderNo);
                
                // 支付失败后的业务逻辑，如恢复库存等
                handlePaymentFailure(order);
            }
            
            orderMapper.updateById(order);
            return true;
        } catch (Exception e) {
            log.error("Payment callback processing failed, orderNo: {}, error: {}", orderNo, e.getMessage(), e);
            // 手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        } finally {
            // 释放分布式锁
            if (locked) {
                redisLockService.unlock(lockKey);
            }
        }
    }
    
    /**
     * 处理支付成功的业务逻辑
     */
    private void handlePaymentSuccess(Order order) {
        try {
            // 1. 通知库存服务确认扣减库存
            // 这里可以通过Dubbo或其他方式调用库存服务
            log.info("Notifying inventory service to confirm stock deduction, orderNo: {}", order.getOrderNo());
            
            // 2. 记录支付日志
            log.info("Recording payment success log, orderNo: {}, transactionId: {}", 
                     order.getOrderNo(), order.getTransactionId());
                      
            // 3. 其他支付成功后的业务逻辑
        } catch (Exception e) {
            log.error("Error handling payment success for orderNo: {}", order.getOrderNo(), e);
            // 这里可以根据实际情况决定是否抛出异常回滚事务
        }
    }
    
    /**
     * 处理支付失败的业务逻辑
     */
    private void handlePaymentFailure(Order order) {
        try {
            // 1. 通知库存服务恢复预留库存
            // 这里可以通过Dubbo或其他方式调用库存服务
            log.info("Notifying inventory service to restore reserved stock, orderNo: {}", order.getOrderNo());
            
            // 2. 记录支付失败日志
            log.info("Recording payment failure log, orderNo: {}, transactionId: {}", 
                     order.getOrderNo(), order.getTransactionId());
                      
            // 3. 其他支付失败后的业务逻辑
        } catch (Exception e) {
            log.error("Error handling payment failure for orderNo: {}", order.getOrderNo(), e);
            // 这里通常不抛出异常，避免影响主流程
        }
    }

    /**
     * 验证创建订单请求参数
     */
    private void validateCreateOrderRequest(CreateOrderRequest request) {
        if (request.getUserId() == null || request.getUserId() <= 0) {
            throw new IllegalArgumentException("用户ID无效");
        }
        if (request.getProductId() == null || request.getProductId() <= 0) {
            throw new IllegalArgumentException("商品ID无效");
        }
        if (request.getQuantity() == null || request.getQuantity() <= 0) {
            throw new IllegalArgumentException("购买数量无效");
        }

        ReceiverInfo receiverInfo = request.getReceiverInfo();
        if (receiverInfo == null) {
            throw new IllegalArgumentException("收货人信息不能为空");
        }
        if (!StringUtils.hasText(receiverInfo.getName())) {
            throw new IllegalArgumentException("收货人姓名不能为空");
        }
        if (!StringUtils.hasText(receiverInfo.getPhone())) {
            throw new IllegalArgumentException("收货人手机号不能为空");
        }
        if (!StringUtils.hasText(receiverInfo.getProvince())) {
            throw new IllegalArgumentException("收货省份不能为空");
        }
        if (!StringUtils.hasText(receiverInfo.getCity())) {
            throw new IllegalArgumentException("收货城市不能为空");
        }
        if (!StringUtils.hasText(receiverInfo.getDistrict())) {
            throw new IllegalArgumentException("收货区/县不能为空");
        }
        if (!StringUtils.hasText(receiverInfo.getAddress())) {
            throw new IllegalArgumentException("详细收货地址不能为空");
        }
    }

    /**
     * 构建包含收货人信息的订单
     */
    private Order buildOrderWithReceiverInfo(CreateOrderRequest request, ProductDTO product) {
        Order order = new Order();
        order.setUserId(request.getUserId());
        order.setOrderNo(generateOrderNo());
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(request.getQuantity())));
        order.setStatus(0); // 待支付

        // 设置收货人信息（使用业务层加密）
        ReceiverInfo receiverInfo = request.getReceiverInfo();

        // 对敏感信息进行AES加密
        order.setReceiverName(aesEncryptionUtil.encrypt(receiverInfo.getName()));
        order.setReceiverPhone(aesEncryptionUtil.encrypt(receiverInfo.getPhone()));
        order.setReceiverAddress(aesEncryptionUtil.encrypt(receiverInfo.getAddress()));

        // 提取手机号前缀和后缀
        String phone = receiverInfo.getPhone();
        if (phone != null && phone.length() >= 7) {
            order.setReceiverPhonePrefix(phone.substring(0, 3));
            order.setReceiverPhoneSuffix(phone.substring(phone.length() - 4));
        } else {
            // 如果手机号格式不正确，设置为空
            order.setReceiverPhonePrefix(null);
            order.setReceiverPhoneSuffix(null);
        }

        // 生成确定性哈希用于索引查询
        order.setReceiverNameHash(aesEncryptionUtil.generateDeterministicHash(receiverInfo.getName()));
        order.setReceiverPhoneHash(aesEncryptionUtil.generateDeterministicHash(receiverInfo.getPhone()));
        order.setReceiverProvince(receiverInfo.getProvince());
        order.setReceiverCity(receiverInfo.getCity());
        order.setReceiverDistrict(receiverInfo.getDistrict());

        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        return order;
    }

    /**
     * 构建订单项
     */
    private OrderItem buildOrderItem(Long orderId, CreateOrderRequest request, ProductDTO product) {
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(orderId);
        orderItem.setProductId(request.getProductId());
        orderItem.setProductName(product.getProductName());
        orderItem.setProductPrice(product.getPrice());
        orderItem.setQuantity(request.getQuantity());
        orderItem.setTotalPrice(product.getPrice().multiply(new BigDecimal(request.getQuantity())));
        return orderItem;
    }

    // 生成订单编号
    private String generateOrderNo() {
        return "ORDER_" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
    }

    // 限流/熔断处理
    public Order createOrderBlockHandler(Long userId, Long productId, Integer quantity, BlockException e) {
        // 记录详细日志用于监控和排查
        log.warn("Order creation blocked due to Sentinel rule, userId: {}, productId: {}, exception: {}"
                , userId, productId, e.getClass().getSimpleName());
        e.printStackTrace();
        // 手动标记事务回滚
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        Order errorOrder = new Order();
        errorOrder.setOrderNo("ERROR_" + System.currentTimeMillis());
        errorOrder.setStatus(-1); // 标识为错误订单
        return errorOrder;
    }

    // 异常处理
    public Order createOrderFallback(Long userId, Long productId, Integer quantity, Throwable e) {
        // 记录详细日志用于监控和排查
        log.warn("Order creation blocked due to Sentinel rule, userId: {}, productId: {}, exception: {}",
                userId, productId, e.getClass().getSimpleName());

        // 手动标记事务回滚
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();


        Order errorOrder = new Order();
        errorOrder.setOrderNo("FALLBACK_" + System.currentTimeMillis());
        errorOrder.setStatus(-2); // 标识为降级订单
        return errorOrder;
    }

    /**
     * 使用业务层加密插入订单
     */
    private void insertOrderWithEncryption(Order order) {
        orderMapper.insertOrderWithEncryption(order);
    }

    /**
     * 根据收货人姓名查询订单
     */
    @DS("slave1")
    public List<Order> findOrdersByReceiverName(String receiverName) {
        String nameHash = aesEncryptionUtil.generateDeterministicHash(receiverName);
        List<Order> orders = orderMapper.findByReceiverNameHash(nameHash);
        // 解密敏感信息
        for (Order order : orders) {
            order.setReceiverName(aesEncryptionUtil.decrypt(order.getReceiverName()));
            order.setReceiverPhone(aesEncryptionUtil.decrypt(order.getReceiverPhone()));
            order.setReceiverAddress(aesEncryptionUtil.decrypt(order.getReceiverAddress()));
        }
        return orders;
    }

    /**
     * 根据收货人手机号查询订单
     */
    @DS("slave1")
    public List<Order> findOrdersByReceiverPhone(String receiverPhone) {
        String phoneHash = aesEncryptionUtil.generateDeterministicHash(receiverPhone);
        List<Order> orders = orderMapper.findByReceiverPhoneHash(phoneHash);
        // 解密敏感信息
        for (Order order : orders) {
            order.setReceiverName(aesEncryptionUtil.decrypt(order.getReceiverName()));
            order.setReceiverPhone(aesEncryptionUtil.decrypt(order.getReceiverPhone()));
            order.setReceiverAddress(aesEncryptionUtil.decrypt(order.getReceiverAddress()));
        }
        return orders;
    }

    /**
     * 根据手机号前缀查询订单
     */
    @DS("slave1")
    public List<Order> findOrdersByReceiverPhonePrefix(String phonePrefix) {
        List<Order> orders = orderMapper.findByReceiverPhonePrefix(phonePrefix);
        // 解密敏感信息
        for (Order order : orders) {
            order.setReceiverName(aesEncryptionUtil.decrypt(order.getReceiverName()));
            order.setReceiverPhone(aesEncryptionUtil.decrypt(order.getReceiverPhone()));
            order.setReceiverAddress(aesEncryptionUtil.decrypt(order.getReceiverAddress()));
        }
        return orders;
    }

    /**
     * 根据手机号后缀查询订单
     */
    @DS("slave1")
    public List<Order> findOrdersByReceiverPhoneSuffix(String phoneSuffix) {
        List<Order> orders = orderMapper.findByReceiverPhoneSuffix(phoneSuffix);
        // 解密敏感信息
        for (Order order : orders) {
            order.setReceiverName(aesEncryptionUtil.decrypt(order.getReceiverName()));
            order.setReceiverPhone(aesEncryptionUtil.decrypt(order.getReceiverPhone()));
            order.setReceiverAddress(aesEncryptionUtil.decrypt(order.getReceiverAddress()));
        }
        return orders;
    }

    /**
     * 根据查询参数进行统一查询
     * 支持手机号（完整、前缀、后缀）、姓名、订单状态等多种条件组合查询
     *
     * @param queryParams 查询参数
     * @return 订单列表
     */
    @DS("slave1")
    @Override
    public List<Order> findOrdersByQueryOrderParams(QueryOrderParams queryParams) {
        // 这里可以复用分页查询的逻辑，只是不进行分页
        Page<Order> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
        Page<Order> resultPage = findOrdersByQueryOrderParams(page, queryParams);
        return resultPage.getRecords();
    }

    /**
     * 根据查询参数进行分页查询
     * 支持手机号（完整、前缀、后缀）、姓名、订单状态等多种条件组合查询
     *
     * @param page        分页参数
     * @param queryParams 查询参数
     * @return 分页结果
     */
    @Override
    @DS("slave1")
    public Page<Order> findOrdersByQueryOrderParams(Page<Order> page, QueryOrderParams queryParams) {
        // 构建查询条件
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

        // 添加手机号查询条件
        if (queryParams.hasPhoneQuery()) {
            int phoneQueryType = queryParams.getPhoneQueryType();
            String phoneValue = queryParams.getPhoneQueryValue();

            switch (phoneQueryType) {
                case 1: // 完整手机号
                    String phoneHash = aesEncryptionUtil.generateDeterministicHash(phoneValue);
                    queryWrapper.eq("receiver_phone_hash", phoneHash);
                    break;
                case 2: // 手机号前缀
                    queryWrapper.eq("receiver_phone_prefix", phoneValue);
                    break;
                case 3: // 手机号后缀
                    queryWrapper.eq("receiver_phone_suffix", phoneValue);
                    break;
            }
        }

        // 添加收货人姓名查询条件
        if (StringUtils.hasText(queryParams.getReceiverName())) {
            String nameHash = aesEncryptionUtil.generateDeterministicHash(queryParams.getReceiverName());
            queryWrapper.eq("receiver_name_hash", nameHash);
        }

        // 添加订单状态查询条件
        if (queryParams.getOrderStatus() != null) {
            queryWrapper.eq("status", queryParams.getOrderStatus());
        }

        // 添加订单号查询条件
        if (StringUtils.hasText(queryParams.getOrderNo())) {
            queryWrapper.eq("order_no", queryParams.getOrderNo());
        }

        // 添加用户ID查询条件
        if (queryParams.getUserId() != null) {
            queryWrapper.eq("user_id", queryParams.getUserId());
        }

        // 添加时间范围查询条件
        if (queryParams.getStartTime() != null) {
            queryWrapper.ge("create_time", queryParams.getStartTime());
        }
        if (queryParams.getEndTime() != null) {
            queryWrapper.le("create_time", queryParams.getEndTime());
        }

        // 执行分页查询
        IPage<Order> resultPage = orderMapper.selectPage(page, queryWrapper);
        // 解密敏感字段
        List<Order> records = resultPage.getRecords();
        for (Order order : records) {
            // 解密收货人姓名和手机号
            order.setReceiverName(aesEncryptionUtil.decrypt(order.getReceiverName()));
            order.setReceiverPhone(aesEncryptionUtil.decrypt(order.getReceiverPhone()));
            order.setReceiverAddress(aesEncryptionUtil.decrypt(order.getReceiverAddress()));
        }
        return (Page<Order>) resultPage;
    }
    
    @Override
    public List<OrderExportDTO> exportOrders(QueryOrderParams queryParams) {
        // 查询订单数据
        List<Order> orders = findOrdersByQueryOrderParams(queryParams);
        
        // 转换为导出DTO
        return orders.stream().map(this::convertToExportDTO).collect(java.util.stream.Collectors.toList());
    }
    
    /**
     * 将Order实体转换为OrderExportDTO
     */
    private OrderExportDTO convertToExportDTO(Order order) {
        OrderExportDTO dto = new OrderExportDTO();
        dto.setOrderNo(order.getOrderNo());
        dto.setUserId(order.getUserId());
        dto.setTotalAmount(order.getTotalAmount());
        dto.setStatus(OrderExportDTO.getStatusDesc(order.getStatus()));
        dto.setReceiverName(order.getReceiverName());
        dto.setReceiverPhone(order.getReceiverPhone());
        dto.setReceiverAddress(buildFullAddress(order));
        dto.setTransactionId(order.getTransactionId());
        dto.setPaymentTime(OrderExportDTO.formatDateTime(order.getPaymentTime()));
        dto.setCreateTime(OrderExportDTO.formatDateTime(order.getCreateTime()));
        return dto;
    }
    
    /**
     * 构建完整的收货地址
     */
    private String buildFullAddress(Order order) {
        StringBuilder addressBuilder = new StringBuilder();
        if (order.getReceiverProvince() != null) {
            addressBuilder.append(order.getReceiverProvince());
        }
        if (order.getReceiverCity() != null) {
            addressBuilder.append(order.getReceiverCity());
        }
        if (order.getReceiverDistrict() != null) {
            addressBuilder.append(order.getReceiverDistrict());
        }
        if (order.getReceiverAddress() != null) {
            addressBuilder.append(order.getReceiverAddress());
        }
        return addressBuilder.toString();
    }
}
